/*
 * Copyright 2008-2017 by Emeric Vernat
 *
 *     This file is part of Java Melody.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.bull.javamelody.swing.table;

import java.util.Collection;
import java.util.Iterator;

/**
 * Définit un renderer pour représenter une List dans une JTable.
 *
 * @author Emeric Vernat
 */
public class MListTableCellRenderer extends MDefaultTableCellRenderer {
	private static final long serialVersionUID = 1L;

	/** {@inheritDoc} */
	@Override
	public void setValue(final Object value) {
		if (value == null) {
			this.setText(null);
		} else if (value instanceof Collection) {
			// Collection inclue ArrayList, HashMap, Vector, Hashtable ...

			// extrait de AbstractCollection.toString pour éviter substring pour enlever []
			final Collection<?> collection = (Collection<?>) value;
			final StringBuilder stringBuffer = new StringBuilder();
			final Iterator<?> iterator = collection.iterator();
			final int maxIndex = collection.size() - 1;
			for (int i = 0; i <= maxIndex; i++) {
				stringBuffer.append(String.valueOf(iterator.next()));
				if (i < maxIndex) {
					stringBuffer.append(", ");
				}
			}
			this.setText(stringBuffer.toString());
		} else {
			this.setText("??");
		}
	}
}
